package com.oromwin.repos.server.response.file;

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.logging.Log;

import com.oromwin.repos.common.Logger;
import com.oromwin.repos.common.ReposConfig;
import com.oromwin.repos.common.ReposException;
import com.oromwin.repos.common.helper.IOHelper;
import com.oromwin.repos.server.response.NormalResponse;

public class ReadFileResponse extends NormalResponse {
    private Log log = Logger.getLog(ReadFileResponse.class);
    private File FilePath = null;
    private long FileBytes = 0L;

    public ReadFileResponse(boolean result, String description, File filePath) {
        Result = result;
        Description = description;
        FilePath = filePath;
    }

    @Override
    public void send(DataOutputStream dos) throws ReposException {
        try {
            dos.writeBoolean(Result);
            IOHelper.writeUTF8(dos, Description);
            FileBytes = FilePath.length();
            dos.writeLong(FileBytes);
            int off = 0;
            int len = ReposConfig.getInstance().getReposSocketIOBuffSize();
            int read = 0;
            byte[] b = new byte[len];
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(FilePath));
            while ((read = bis.read(b, off, len)) > 0) {
                dos.write(b, off, read);
            }
            dos.flush();
        } catch (IOException e) {
            throw ReposException.create(log, e);
        }
    }
    
    public File getFilePath() {
        return FilePath;
    }
}
